package com.ezops.poc.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository(value = "fieldMappingDAO")
public class FieldMappingDAO {

	private static final Logger logger = LoggerFactory
			.getLogger(FieldMappingDAO.class);

	private static final String GET_MAPPING_QUERY = "SELECT B.FIELD_NAME as EZOPSFIELD, C.FIELD_NAME as CLIENTFIELD FROM EZOPSDB.EZOPS_CLIENT_FIELD_MAPPING A , "
			+ "EZOPSDB.EZOPS_FIELDS B, EZOPSDB.CLIENT_FIELDS C where A.EZOPS_FIELD_ID=B.FIELD_ID and A.CLIENT_FIELD_ID = C.FIELD_ID and C.CLIENT_ID =? ";

	@Autowired
	private JdbcTemplate jdbcTemplate;

	public FieldMappingDAO() {
	}

	/**
	 * Retrieve the mapping present for the given client and asset class. return
	 * a map with key as ezops field and value as client field.
	 * 
	 * @param clientId
	 * @param assetId
	 * @return
	 */
	public Map<String, String> getMapping(int clientId, int assetId) {
		logger.trace("Retrieving mapping for client id {} and assetId {}", clientId, assetId);
		List<Map<String, Object>> results = jdbcTemplate.queryForList(
				GET_MAPPING_QUERY, clientId);
		return merge(results);
	}

	private Map<String, String> merge(List<Map<String, Object>> results) {
		HashMap<String, String> finalMapping = new HashMap<String, String>(
				results.size());
		for (Map<String, Object> mapping : results) {
			finalMapping.put(mapping.get("EZOPSFIELD").toString(),
					mapping.get("CLIENTFIELD").toString());

		}
		return finalMapping;
	}

}
